/**
 * Created by yesi on 15/5/16.
 */
var cookie_uid = "uid";
var success = 1;
var fail = 0;

function createSuccessData(data){
    var obj = new Object();
    obj.status = success;
    obj.data = data;
    obj.msg = "";
    return JSON.stringify(obj);
}

function createFailData(msg){
    var obj = new Object();
    obj.status = fail;
    obj.data = "";
    obj.msg = msg;
    return JSON.stringify(obj);
}

function createRData(flag,data,msg){
    var obj = new Object();
    obj.status = flag;
    obj.data = data;
    obj.msg = msg;
    return JSON.stringify(obj);
}

function write404(response){
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
}

function write200(response,data){
    response.statusCode = 200;
    response.write(data);
    response.end();
}

function setHeader(response,key,value){
    response.setHeader(key,value);
}

function bindCookie(request,response,domain){
    var Cookies = {};
    request.headers.cookie && request.headers.cookie.split(';').forEach(function( Cookie ) {
        var parts = Cookie.split('=');
        Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    });
    var myCookie = "";
    if(Cookies[cookie_uid]==null){
        var cookie = generateCookie();
        setHeader(response,'Set-Cookie',cookie_uid+'='+cookie);
        myCookie = cookie;
    }else{
        myCookie = Cookies[cookie_uid];
    }

    domain.cookie = myCookie;
}

//用时间来解决不重复的随机数问题，不过这里用uuid会更好一些 by yesi
function generateCookie(){
    return (new Date().getTime()) ^ Math.random();
}

exports.createFailData = createFailData;
exports.createRData = createRData;
exports.createSuccessData = createSuccessData;
exports.write404 = write404;
exports.write200 = write200;
exports.setHeader = setHeader;
exports.bindCookie = bindCookie;
